package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.warning.domain.entity.Mempool;
import com.ruoyi.warning.domain.entity.Processor;
import com.ruoyi.warning.domain.entity.Threshold;
import com.ruoyi.warning.mapper.ThresholdMapper;
import com.ruoyi.warning.service.IMempoolsService;
import com.ruoyi.warning.service.IProcessorsService;
import com.ruoyi.warning.service.IThresholdService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 阈值表 服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-03-25
 */
@Service
public class ThresholdServiceImpl extends ServiceImpl<ThresholdMapper, Threshold> implements IThresholdService {

    @Resource
    private IProcessorsService processorsService;
    @Resource
    private IMempoolsService mempoolsService;
    @Override
    public Object getAllThresholds(Integer deviceId) {
        LambdaQueryWrapper<Threshold> wrapper = new QueryWrapper<Threshold>().lambda()
                .eq(Threshold::getDeviceId, deviceId);
        List<Threshold> list = this.list(wrapper);
        return list;
    }

    @Override
    public Object updateThresholds(List<Threshold> list) {
        this.saveOrUpdateBatch(list);
        // 修改cpu和内存报警值
        for (Threshold threshold : list) {
            if (threshold.getType().equals("CPU利用率")) {
                LambdaUpdateWrapper<Processor> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Processor::getDeviceId, threshold.getDeviceId());
                wrapper.set(Processor::getProcessorPercWarn, threshold.getRedWarning());
                processorsService.update(wrapper);
            } else if (threshold.getType().equals("内存利用率")) {
                LambdaUpdateWrapper<Mempool> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Mempool::getDeviceId, threshold.getDeviceId());
                wrapper.set(Mempool::getMempoolPercWarn, threshold.getRedWarning());
                mempoolsService.update(wrapper);
            }
        }
        return "successful";
    }
}
